<template>
  <view class="layout">
    <!-- #ifdef APP-PLUS -->
    <u-sticky :offsetTop="0">
      <view class="header">司机 <text> - {{driver.mobile}}</text></view>
    </u-sticky>
    <!-- #endif -->
    <!-- #ifdef H5 -->
    <view class="header">司机 <text> - {{driver.mobile}}</text></view>
    <!-- #endif -->
    <view class="order" v-if="active === 0">
      <!-- #ifdef APP-PLUS -->
      <u-sticky :offsetTop="'190rpx'">
        <view class="tab">
          <u-subsection
              mode="subsection"
              bgColor="#f7f8f9"
              inactiveColor="#666666"
              :activeColor="'red'"
              :list="tabs"
              @change="changeIndex"
              :current="current"
              fontSize="24rpx"></u-subsection>
          <view class="search">
            <view class="type">
              <u-button :text="selectedText" @click="showSearchType=true" size="small"></u-button>
            </view>
            <view class="s">
              <u-search
                  placeholder="请输入关键字"
                  v-model="keyword"
                  height="60rpx"
                  searchIconSize="50rpx"
                  @search="onSearch"
                  @custom="onSearch"
                  @clear="clearSearch"
              ></u-search>
            </view>
          </view>
        </view>
      </u-sticky>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view class="tab">
        <u-subsection
            mode="subsection"
            bgColor="#f7f8f9"
            inactiveColor="#666666"
            :activeColor="'red'"
            :list="tabs"
            @change="changeIndex"
            :current="current"
            fontSize="24rpx"></u-subsection>
        <view class="search">
          <view class="type">
            <u-button :text="selectedText" @click="showSearchType=true" size="small"></u-button>
          </view>
          <view class="s">
            <u-search
                placeholder="请输入关键字"
                v-model="keyword"
                height="60rpx"
                searchIconSize="50rpx"
                @search="onSearch"
                @custom="onSearch"
                @clear="clearSearch"
            ></u-search>
          </view>
        </view>
      </view>
      <!-- #endif -->
      <view class="top"></view>
      <view class="list" v-if="orderList.length > 0">
        <view class="item" v-for="(item, index) in orderList" :key="index">
          <view class="sn">订单号: {{item.sn}}</view>
          <view class="time">{{ item.create_time }}</view>
          <view class="name" v-if="item.address">收货人: <text>{{item.address.nickname}}</text></view>
          <view class="mobile" v-if="item.address">电话: <text>{{item.address.mobile}}</text></view>
          <view class="address" v-if="item.address && item.address.city">收货地址:
              {{item.address.city.province}}
              {{item.address.city.city}}
              {{item.address.city.area}}
              {{item.address.address}}
          </view>
          <view class="product" v-for="(o, i) in item.item" :key="i">
            <template v-if="o.product">
              <view class="image">
                <u--image
                    class="img"
                    lazy-load width="160rpx"
                    height="160rpx"
                    :fade="true" duration="450"
                    :src="baseUrl + o.sku.image.thumbnail_path"
                    v-if="o.sku && o.sku.image"></u--image>
                <u--image
                    class="img"
                    lazy-load width="160rpx"
                    height="160rpx"
                    :fade="true" duration="450"
                    :src="baseUrl + o.product.mainImage.thumbnail_path"
                    v-else-if="o.product.mainImage"></u--image>
              </view>
              <view class="desc">
                <view class="title two-lines">{{ o.product.title }}</view>
                <view class="sku" v-if="o.selected_sku_text && Array.isArray(o.selected_sku_text)">
                  {{ o.selected_sku_text.join(', ') }}
                  x
                  {{ o.quantity }}
                </view>
                <view class="price">
                  价格: <text class="unit">￥</text><text>{{ o.price * 1 }}</text>
                </view>
                <view class="quantity">
                  数量: <text class="unit">x</text><text>{{ o.quantity * 1 }}</text>
                </view>
              </view>
            </template>
          </view>
          <view class="status">
            <view class="text">{{ item | statusText }}</view>
          </view>
          <view class="ops">
            <view class="amount" v-if="item.express_status * 1 === 3">
              应收金额:<text class="unit">￥</text>
              <text>{{ item.total_pay * 1 }}</text>
            </view>
            <view class="btn">
              <view class="x" v-if="item.express_status * 1 === 0">
                <u-button class="" text="操作入库" size="small" type="primary" @click="into(item)"></u-button>
              </view>
              <view class="x" v-if="item.express_status * 1 === 1">
                <u-button class="" text="操作出库" size="small" type="primary" @click="out(item)"></u-button>
              </view>
              <view class="x" v-if="item.express_status * 1 === 2">
                <u-button class="" text="完成送到" size="small" type="primary" @click="received(item)"></u-button>
              </view>
              <view class="x y" v-if="item.express_status * 1 === 3">
                <u-button class="" text="完成收款" size="small" type="primary" @click="pay(item)"></u-button>
                <view class="k"></view>
                <u-button class="" text="取消送到" size="small" type="warning " @click="cancelReceived(item)"></u-button>
              </view>
              <view class="x" v-if="item.express_status * 1 === 10">
                <u-button class="" text="取消收款" size="small" type="warning " @click="cancelPay(item)"></u-button>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="nothing" v-else>暂无信息...</view>
    </view>
    <view class="scan" v-if="active === 1">
      <u-gap height="30" bgColor="'white'"></u-gap>
      <u-button text="商品扫描入库" type="success" @click="scanInto" :customStyle="{'height': '50px'}"></u-button>
      <u-gap height="30" bgColor="'white'"></u-gap>
      <u-button text="商品扫描出库" type="warning" @click="scanOut" :customStyle="{'height': '50px'}"></u-button>
      <u-gap height="30" bgColor="'white'"></u-gap>
      <view class="msg">{{msg}}</view>
      <!--<view class="msg">{{scanResult.error_text}}</view>-->
      <view class="order">
        <view class="sn" v-if="scanResult.order.sn">订单号: {{scanResult.order.sn}}</view>
        <view class="sn" v-if="scanResult.order.total > 0">总数量: {{scanResult.order.total}}</view>
        <view class="product" v-if="scanResult.order.list.length > 0">
          <view class="t">商品详情:</view>
          <view class="item" v-for="(item, index) in scanResult.order.list">
            {{item.name}} x {{item.quantity}}
          </view>
        </view>
      </view>
    </view>
    <view class="setting" v-if="active === 2">
      <u-button text="退出登录" type="primary" @click="logout"></u-button>
    </view>
    <view class="footer">
      <view class="item" :class="{'active': active === 0}" @click="handleTab(0)">
        <u--image
            width="40rpx"
            height="40rpx"
            mode="widthFix"
            :src="tab1" />
        <view class="text">订单</view>
      </view>
      <view class="item" :class="{'active': active === 1}" @click="handleTab(1)">
        <u--image
            width="40rpx"
            height="40rpx"
            mode="widthFix"
            :src="tab2" />
        <view class="text">扫码</view>
      </view>
      <view class="item" :class="{'active': active === 2}" @click="handleTab(2)">
        <u--image
            width="40rpx"
            height="40rpx"
            mode="widthFix"
            :src="tab3" />
        <view class="text">设置</view>
      </view>
    </view>
    <u-back-top bottom="150" :scroll-top="scrollTop" icon="arrow-up" :customStyle="{'opacity': '0.88'}"></u-back-top>
    <u-picker title="请选择搜索类型" :show="showSearchType" :columns="searchType" :keyName="'label'" itemHeight="100"
      @close="showSearchType= false " @cancel="showSearchType = false" @confirm="selectType"></u-picker>
  </view>
</template>

<script>
import config from '../../config/config'
import * as cache from '../../util/cache'
import Driver from '../../api/driver'
import base64 from '../../util/base64'

const driverModel = new Driver()

export default {
  computed: {
    tab1() {
      return this.active === 0 ? '/static/driver/order-active.png' : '/static/driver/order.png'
    },
    tab2() {
      return this.active === 1 ? '/static/driver/scan-active.png' : '/static/driver/scan.png'
    },
    tab3() {
      return this.active === 2 ? '/static/driver/set-active.png' : '/static/driver/set.png'
    }
  },
  filters: {
    statusText(v) {
      switch (+v.express_status) {
        case 0:
          return '待入库'
        case 1:
          return '待出库'
        case 2:
          return '待收货'
        case 3:
          return '待支付'
        case 10:
          return '已完成'
      }
    },
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  data() {
    return {
      // 这里全部用物流状态, 待支付就是已收货, 支付完成了, 就是已完成
      // 支付了, status = 1
      // 退货, status = 6
      tabs: ['全部', '待入库', '待出库', '待收货', '待支付', '已完成'],
      current: 0,
      baseUrl: config.baseUrl,
      scrollTop: 0,
      id: 0,
      active: 0,
      driver: {},
      // menu: [],
      // menuChildren: [],
      // currentIndex: 0,
      orderList: [],
      queryList: {
        page: 0,
        pageSize: 10,
        busy: false
      },
      // 搜索
      keyword: '',
      searchType: [[
        { label: '商品', id: 1 },
        { label: '电话', id: 2 },
        { label: '收件人', id: 3 },
      ]],
      showSearchType: false,
      selectedText: '商品',
      selectedValue: 1,
      // 提示文字
      msg: '',
      // 扫码结果
      scanResult: {
        success_text: '',
        error_text: '',
        status: 0,
        order: {
          sn: '',
          total: 0,
          list: [],
        }
      }
    }
  },
  // 下拉更多
  onReachBottom() {
    this.getOrderList(true)
  },
  onLoad() {
    const id = cache.get('driver')
    this.id = id
    this.getInfo()
    this.getOrderList()
  },
  onShow() {
    const id = cache.get('driver')
    this.id = id
    if (!id) {
      uni.navigateTo({
        url: '/sub_common/user/login'
      })
    }
  },
  methods: {
    changeIndex(index) {
      this.current = index
      this.orderList = []
      this.queryList = {
        page: 0,
            pageSize: 10,
            busy: false
      }
      console.log(this.current)
      this.getOrderList()
    },
    handleTab(index) {
      this.active = index
      if (index === 1) {
      }
    },
    // 退出登录
    logout() {
      cache.remove('driver')
      uni.navigateTo({
        url: '/sub_common/user/login'
      })
    },
    // 获取信息
    getInfo() {
      driverModel.getInfo({ id: this.id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.driver = data.driver
        // console.log(data)
      })
    },
    // 订单
    getOrderList(append = false) {
      if (this.queryList.busy === false) {
        this.queryList.page++
        this.queryList.busy = true
        driverModel.getOrderList({ id: this.id, ...this.queryList, status: this.current, type: this.selectedValue, key: this.keyword }).then(response => {
          let { data } = response
          data = base64.parse(data)
          if (data.list.length === 0) {
            this.queryList.busy = true
          } else {
            this.queryList.busy = false
            if (append) {
              this.orderList = this.orderList.concat(data.list)
            } else {
              this.orderList = data.list
            }
            // console.log(this.orderList)
          }
        }).finally(() => {
          uni.stopPullDownRefresh();
        })
      }
    },
    selectType(e) {
      this.showSearchType = false
      const { value } = e
      const id = value[0].id
      const text = value[0].label
      this.selectedText = text
      this.selectedValue = id
      // console.log(e)
    },
    clearSearch() {
      this.orderList = []
      this.queryList = {
        page: 0,
        pageSize: 10,
        busy: false
      }
      this.getOrderList()
    },
    // 搜索订单
    onSearch(e) {
      if (this.keyword) {
        this.orderList = []
        this.queryList = {
          page: 0,
          pageSize: 10,
          busy: false
        }
        this.getOrderList()
      } else {
        uni.showToast({
          icon: 'none',
          title: '请输入关键字'
        })
      }
    },
    // 入库
    into(item) {
      driverModel.into({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 1)
        this.changeIndex(2)
      })
    },
    // 出库
    out(item) {
      driverModel.out({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 2)
        this.changeIndex(3)
      })
    },
    // 收货
    received(item) {
      driverModel.received({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 3)
        this.changeIndex(4)
      })
    },
    // 支付
    pay(item) {
      driverModel.pay({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 10)
        this.changeIndex(5)
      })
    },
    // 取消收货
    cancelReceived(item) {
      driverModel.cancelReceived({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 3)
        this.changeIndex(3)
      })
    },
    // 取消支付
    cancelPay(item) {
      driverModel.cancelPay({ driver: this.id, id: item.id }).then(() => {
        uni.showToast({
          icon: 'none',
          title: '操作成功'
        })
        this.$set(item, 'express_status', 4)
        this.changeIndex(4)
      })
    },
    // 商品扫码入库
    scanInto() {
      //#ifdef H5
      return uni.showToast({
        icon: 'none',
        title: '请使用APP扫码!'
      })
      //#endif
      this.scanResult = {
        success_text: '',
        error_text: '',
        status: 0,
        order: {
          sn: '',
          total: 0,
          list: [],
        }
      }
      this.msg = ''
      uni.scanCode({
        success: res => {
          // 扫出来的结果是string
          let obj = res.result
          console.log(222, JSON.parse(obj), this.id)
          obj = JSON.parse(obj)
          // this.msg = JSON.stringify(obj)
          driverModel.scanInto({ ...obj, id: this.id }).then(response => {
            const { data } = response
            this.msg = data.text || ''
            this.scanResult.order = data.order
            this.scanResult.status = data.status
            this.scanResult.sn = obj.order_sn
            uni.showToast({
              icon: 'none',
              title: '操作成功!'
            })
          }).catch(err => {
            uni.showToast({
              icon: 'none',
              title: err.message
            })
            this.scanResult.error_text = err.message
            this.msg = err.message
          })
        }
      })
    },
    scanOut() {
      //#ifdef H5
      return uni.showToast({
        icon: 'none',
        title: '请使用APP扫码!'
      })
      //#endif
      this.scanResult = {
        success_text: '',
        error_text: '',
        status: 0,
        order: {
          sn: '',
          total: 0,
          list: [],
        }
      }
      this.msg = ''
      uni.scanCode({
        success: res => {
          // 扫出来的结果是string
          let obj = res.result
          console.log(222, JSON.parse(obj), this.id)
          obj = JSON.parse(obj)
          // this.msg = JSON.stringify(obj)
          driverModel.scanOut({ ...obj, id: this.id }).then(response => {
            const { data } = response
            this.msg = data.text || ''
            this.scanResult.order = data.order
            this.scanResult.status = data.status
            this.scanResult.sn = obj.order_sn
            uni.showToast({
              icon: 'none',
              title: '操作成功!'
            })
          }).catch(err => {
            uni.showToast({
              icon: 'none',
              title: err.message
            })
            this.scanResult.error_text = err.message
            this.msg = err.message
          })
        }
      })
    },
  },
  // 刷新
  onPullDownRefresh() {
    if (this.active === 0) {
      this.orderList = []
      this.queryList = {
        page: 0,
        pageSize: 10,
        busy: false
      }
      this.getOrderList()
    } else {
      uni.stopPullDownRefresh();
    }
  }
}
</script>

<style scoped lang="scss">
$header: 90rpx;
.header {
  /* #ifdef APP-PLUS */
  padding-top: 90rpx;
  /* #endif */
  height: $header;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 3rpx;
  font-weight: 700;
  color: white;
  text {
    font-weight: normal;
    margin-left: 20rpx;
  }
}
.tab {
  background: white;
  height: 35px;
  padding: 5px 10px;
  position: sticky;
  top: 0;
  z-index: 100;
  .search {
    background: white;
    padding: 20rpx 0;
    display: flex;
    align-items: center;
    .type {
      //background: red;
      width: 200rpx;
      margin-right: 20rpx;
    }
    .s {
      flex: 1;
    }
  }
}
.footer {
  height: 100rpx;
  //background: red;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  border-top: 1rpx solid #f4f6f8;
  display: flex;
  align-items: center;
  justify-content: space-around;
  z-index: 100;
  background: white;
  .item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    &.active {
      color: red;
    }
  }
}
.setting {
  padding: 100rpx 50rpx 0 50rpx;
}
.order {
  padding: 20rpx;
  //background: red;
  //margin-bottom: 120rpx;
  padding-bottom: 120rpx;
  background: #f3f5f7;
  .top {
    height: 80rpx;
    background: white;
  }
  .nothing {
    height: 100px;
    color: #666666;
    text-align: center;
    padding-top: 50px;
  }
  .item, .nothing {
    background: white;
    padding: 20rpx;
    border-radius: 10rpx;
    margin-bottom: 10px;
    .name, .mobile, .address {
      margin-top: 10rpx;
      text {
        color: red;
        margin-left: 10rpx;
      }
    }
    .status {
      //background: red;
      padding: 20rpx 0;
      .text, .group, .win {
        display: inline-block;
        background: $main_color;
        padding: 5rpx 10rpx;
        color: white;
        margin-right: 10px;
      }
      .group {
        background: red;
        &.done {
          background: #f3f5f7;
          color: #000000;
        }
      }
      .win {
        background: red;
        &.not {
          background: #f3f5f7;
          color: #000000;
        }
      }
    }
    .sn {
      font-weight: 700;
    }
    .time {
      color: #999999;
      margin-top: 10rpx;
    }
    .product {
      display: flex;
      margin-top: 10px;
      .image {
        width: 160rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .img {
          display: block;
        }
      }
      .desc {
        flex: 1;
        padding-left: 10px;
        display: flex;
        flex-direction: column;
        align-items: start;
        justify-content: center;
        .title, .sku, .price {
          height: 20px;
        }
        .title {
          font-weight: 700;
          font-size: 26rpx;
        }
        .sku {
          color: #999;
        }
        .price {
          margin: 10rpx 0;
          text {
            font-weight: 500;
            //font-size: 26rpx;
          }
          .unit {
            font-size: 20rpx;
            margin-left: 10rpx;
          }
          .split {
            //background: red;
            //height: 20px;
            width: 10px;
            display: inline-block;
          }
        }
        .quantity {
          .unit {
            margin-left: 10rpx;
          }
          text {
            color: red;
          }
        }
      }
    }
    .ops {
      height: 50px;
      //background: red;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .amount {
        width: 300rpx;
        text {
          font-weight: 700;
          font-size: 32rpx;
          color: red;
        }
        .unit {
          font-size: 20rpx;
          margin-left: 10rpx;
        }
      }
      .btn {
        flex: 1;
        display: flex;
        //background: red;
        justify-content: flex-end;
        //justify-content: space-between;
        .x {
          letter-spacing: 1px;
          margin-left: 5px;
        }
        .y {
          //background: red;
          width: 300rpx;
          display: flex;
          .k {
            width: 30rpx;
          }
        }
      }
    }
  }
}
.scan {
  margin: 10px;
  .msg {
    color: red;
    margin: 10px 0;
  }
}
</style>
